# -*- coding: utf-8 -*-
"""
超市销售数据分析
实验17 为累计消费前10的顾客画像
@author: tange
"""

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

data = pd.read_csv(r'C:\大数据分析综合实训-附件.csv', encoding='gbk')

# 消费前10顾客
task17_1_data = data[['顾客编号', '销售金额']]

list_customer = task17_1_data['顾客编号'].unique()

sum_list = []
for i in list_customer:
    sum_customer = (task17_1_data[task17_1_data['顾客编号'] == i].销售金额.sum())
    sum_list.append(sum_customer)

# 累计消费前10的顾客id列表
top_sale_customer_id_list = []
# 累计消费前10的顾客的累计销售金额列表
top_sale_customer_volume_list = []

for i in range(10):
    max_sum = max(sum_list)
    top_sale_customer_volume_list.append(max_sum)

    location = sum_list.index(max_sum)

    top_sale_customer_id_list.append(list_customer[location])

    sum_list[sum_list.index(max_sum)] = 0

# 任务1 消费前10顾客的消费金额总量
fig, ax = plt.subplots()
ax.set_title("不同客户的消费金额总量")
y_pos = np.arange(len(top_sale_customer_id_list))

ax.barh(y_pos, top_sale_customer_volume_list, align='center')  # 水平柱状

ax.invert_yaxis()  # 反转Y轴

ax.set_yticks(y_pos)
ax.set_yticklabels(top_sale_customer_id_list, fontsize=13)
ax.set_xlabel('销量')

# 任务2 顾客消费种类占比(饼图)
task17_2_data = data[['顾客编号', '中类名称']]
for id in top_sale_customer_id_list:
    fig, ax1 = plt.subplots()
    task17_2_data[task17_2_data['顾客编号'] == id].中类名称.value_counts().plot(
        kind='pie', ax=ax1, rot=50, figsize=(15, 10), fontsize=11, title=str(id) + '顾客消费种类占比')


# 任务3 顾客是否购买促销商品占比
task17_3_data = data[['顾客编号', '是否促销']]
order_count_list = []
labels = ['否', '是']
for i in top_sale_customer_id_list:
    count = list(task17_3_data[task17_3_data['顾客编号'] == i].是否促销.value_counts())
    order_count_list.append(count)
for i in range(len(order_count_list)):
    fig, ax = plt.subplots()
    ax.set_title(str(top_sale_customer_id_list[i]) + '顾客是否购买促销商品占比')
    ax.pie(order_count_list[i], labels=labels)

# 任务4 顾客月度购买商品占比
task17_4_data = data[['顾客编号', '销售月份', '中类名称']]
for id in top_sale_customer_id_list:
    for m in [201501, 201502, 201503, 201504]:
        try:
            counts = task17_4_data[task17_4_data['销售月份'] == m][task17_4_data['顾客编号'] == id].中类名称.value_counts()
            if len(counts) > 0:
                fig, ax = plt.subplots()
                print(list(counts))
                counts.plot(kind='pie', figsize=(20, 10), rot=35, fontsize=15, title=str(id) + '号顾客' + str(m)[4:] + '月购物情况')
        except:
            pass


# # 任务2 顾客消费种类占比(柱状图)
# task17_2_data = data[['顾客编号', '中类名称']]
# for id in top_sale_customer_id_list:
#     fig, ax1 = plt.subplots()
#     task17_2_data[task17_2_data['顾客编号'] == id].中类名称.value_counts().plot(
#         kind='bar', ax=ax1, rot=50, figsize=(15, 10), fontsize=11)